<?php

namespace app\common\model\ads;

use think\Model;
use think\Cache;
use app\common\model\TxArea;

class Ad extends Model
{

    // 表名
    protected $name = 'self_ad';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'images',
        'type_text',
        'category_text',
        'effecttime_text',
        'createtime_text',
        'toptime_text',
        'status_text',
        'display_text',
        'recommendtime_text',
        'range_text'
    ];

    protected static function init()
    {
        Ad::event('after_insert', function ($ad) {
            if ($ad->category == 1 && $ad->id) {
                try {
                    \turbo\Video::dealAd($ad->id);
                } catch (\Exception $th) {
                    
                }
            }
        });
    }

    public function getTypeList()
    {
        return ['1' => "赏金广告", '2' => "公益广告"];
    }

    public function getCategoryList()
    {
        return ['1' => "视频", '2' => "图文"];
    }

    public function getStatusList()
    {
        return ['0' => "待审核", '1' => "审核通过", '2' => "审核未通过"];
    }

    public function getDisplayList()
    {
        return ['0' => __('Display 0'), '1' => __('Display 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCategoryTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['category']) ? $data['category'] : '');
        $list = $this->getCategoryList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getEffecttimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['effecttime']) ? $data['effecttime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getToptimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['toptime']) ? $data['toptime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getDisplayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['display']) ? $data['display'] : '');
        $list = $this->getDisplayList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getRecommendtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['recommendtime']) ? $data['recommendtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setEffecttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setToptimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setRecommendtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getRangeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['range']) ? $data['range'] : '');
        if ($value == 0) {
            return '同城';
        } else {
            return $value . '公里';
        }
    }


    public function getMoneyMarkAttr($value, $data)
    {
        $type = isset($data['type']) ? $data['type'] : 0;
        $get_num = isset($data['get_num']) ? $data['get_num'] : 0;
        $money_count = isset($data['money_count']) ? $data['money_count'] : 0;
        $effecttime = isset($data['effecttime']) ? $data['effecttime'] : 0;

        $money_mark = 0;

        if ($type == 1) {
            $money_mark = 1;    //正在领取
            if ($effecttime < time()) {
                $money_mark = 2;    //有效期结束
            } else if ($get_num == $money_count) {
                $money_mark = 3;    //已领完
            }
        }

        return $money_mark;
    }

    public function getFavoriteNumAttr($value, $data)
    {
        $value = isset($data['id']) ? $data['id'] : 0;
        return $value ? \think\Db::name('self_favorite')->where([
            'type' => 0,
            'data_id' => $value,
        ])->count() : 0;
    }

    public function getCommentNumAttr($value, $data)
    {
        $value = isset($data['id']) ? $data['id'] : 0;
        return $value ? \think\Db::name('self_comment')->where(['ad_id' => $value])->count() : 0;
    }

    public function getImagesAttr($value, $data)
    {
        if (isset($data['images'])) return $data['images'];
        // $files = isset($data['files']) ? $data['files'] : "";
        // $res = [];
        // $list = explode(",", $files);
        // foreach ($list as $key => $value) {
        //     if ($value) {
        //         $res[] = cdnurl($value);
        //     }
        // }
        $files = isset($data['file_list']) ? $data['file_list'] : $this->getFileListAttr($value, $data);
        return $files ? array_column($files,'cdn_url') : [];
    }


    public function getFileListAttr($value, $data)
    {
        $res = [];
        $files = isset($data['files']) ? $data['files'] : "";
        $list = explode(",", $files);
        foreach ($list as $key => $value) {
            if ($value) {
                $res[] = [
                    'file_url' => $value,
                    'cdn_url' => cdnurl($value,\think\Config::get('site.cdnurl')),
                ];
            }
        }
        // if(isset($data['category']) && $data['category'] == 1){
        //     #视频类的调整顺序
        //     if(isset($res[0]) && isset($res[1])){
        //         return [$res[1], $res[0]];
        //     }
        // }
        return $res;
    }

    public function getUserInfoAttr($value, $data)
    {
        $value = isset($data['user_id']) ? $data['user_id'] : 0;
        return $value ? \app\common\model\User::getBaseInfoNosense($value) : new \stdClass();
    }

    public function getOrderAttr($value, $data)
    {
        $id = isset($data['id']) ? $data['id'] : 0;
        return $id ? \app\common\model\ads\Order::createOrder($id) : null;
    }

    public function getEffecttimeDayAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : 0;
        $effecttime = isset($data['effecttime']) ? $data['effecttime'] : 0;
        if ($effecttime && $createtime) {
            $effecttime = intval(($effecttime - $createtime) / 86400);
            return $effecttime;
        }
        return 0;
    }

    public function getToptimeDayAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : 0;
        $effecttime = isset($data['toptime']) ? $data['toptime'] : 0;
        if ($effecttime && $createtime) {
            $effecttime = intval(($effecttime - $createtime) / 86400);
            return $effecttime;
        }
        return 0;
    }

    public function getRecommendtimeDayAttr($value, $data)
    {
        $createtime = isset($data['createtime']) ? $data['createtime'] : 0;
        $effecttime = isset($data['recommendtime']) ? $data['recommendtime'] : 0;
        if ($effecttime && $createtime) {
            $effecttime = intval(($effecttime - $createtime) / 86400);
            return $effecttime;
        }
        return 0;
    }

    public function getIsPaydoneAttr($value, $data)
    {
        $id = isset($data['id']) ? $data['id'] : 0;
        if ($id) {
            $order = \app\common\model\ads\Order::where('ad_id', $id)->where('status', 1)->find();
            if ($order) {
                return true;
            }
        }
        return false;
    }

    /**
     * 金币被领取份数
     */
    public function getRedpackGetNumAttr($value, $data){
        $type = isset($data['type']) ? $data['type'] : 0;
        $id = isset($data['id']) ? $data['id'] : 0;

        if($type == 1 && $id){
            return \app\common\model\ads\GoldLog::where('ad_id', $id)->where('user_id','>', 0)->count();
        }

        return 0;
    }

    public function getAreaTextAttr($value, $data)
    {
        $id = isset($data['id']) ? $data['id'] : 0;

        $hash = null;

        if($id){
            $hash = "AD_AREA_ATTR_{$id}";
        }

        if($hash){
            $cache = Cache::get($hash);
            if($cache) return $hash;
        }

        $province = isset($data['province']) ? $data['province'] : 0;
        $city = isset($data['city']) ? $data['city'] : 0;
        $county = isset($data['county']) ? $data['county'] : 0;
        if($county) {
            $cache = TxArea::getAddressByCode($county);

            if($hash){
                Cache::set($hash, $cache, 600);
            }
            return $cache;
        }
        if($city) {
            $cache = TxArea::getAddressByCode($county);
            if($hash){
                Cache::set($hash, $cache, 600);
            }
            return $cache;
        }
        if($province) {
            $cache = TxArea::getAddressByCode($province);
            if($hash){
                Cache::set($hash, $cache, 600);
            }
            return $cache;
        }
        return '';
    }
}
